/**？
 * 作者：王东磊
 * 功能：用于分页显示，自带分页，模糊查询功能
 * 使用说明:1.导入pageNation.js
 *         2.使用pageNation.init(JSON)方法初始化分页对象  JSON格式: {url:'后台代码地址',clom:'表格的基本信息'}
 * 举例:
 *  <script src="./lib/jquery/dist/jquery.min.js"></script>
 *  <script src="./js/pageNation.js"></script>
 *         pageNation.init({
        clom:[
            {chinesename:'简历表id',colname:'jid',wide:'short',type:'NUMBER'},
            {chinesename:'投递人id',colname:'pid',wide:'short',type:'VARCHAR'},
            {chinesename:'投递人姓名',colname:'pname',wide:'middle',type:'VARCHAR'},
            {chinesename:'投递人性别',colname:'psex',wide:'short',type:'VARCHAR'},
            {chinesename:'投递人年龄',colname:'pbirth',wide:'long',type:'DATE'},
            {chinesename:'投递人户籍',colname:'pcity',wide:'long',type:'VARCHAR'},
            {chinesename:'投递人联系方式',colname:'pcall',wide:'long',type:'VARCHAR'},
            {chinesename:'投递人邮箱',colname:'pmail',wide:'long',type:'VARCHAR'},
            {chinesename:'简历',colname:'position',wide:'long',type:'VARCHAR'},
            {chinesename:'公司id',colname:'cid',wide:'long',type:'VARCHAR'},
            {chinesename:'公司名称',colname:'cname',wide:'long',type:'VARCHAR'},
            {chinesename:'公司提供的薪资',colname:'cpay',wide:'long',type:'NUMBER'},
            {chinesename:'就业状态',colname:'state',wide:'middle',type:'status',pool:{'未就业':0,'已就业':1}}
        ],
        primaryKey:'jid',
        url:[
            {insert:'/pageNation/insert'},
            {select:'/pageNation/pageNation'},
            {delete:'/pageNation/delete'},
            {update:'/pageNation/update'},
            {freeze:'/pageNation/freeze'},
            {pass:'/pageNation/pass'}
        ],
        operation:[
            {chinesename:'删除',type:'delete',wide:'short'},
            {chinesename:'编辑',type:'update',wide:'short'},
            {chinesename:'冻结',type:'freeze',wide:'short'},
            {chinesename:'通过',type:'pass',wide:'short'}
        ],
        toolBar:[
            {chinesename:'添加',type:'insert',wide:'short',icon:''}
        ],title:'已就业学生信息',
        positionId:'body',
        selectCondition:[
        {
            conditionName:'pid',
            operator:'is not',
            value:'null'
            },
            {
            conditionName:'state',
            operator:'=',
            value:'1'
            }
        ]
    });
*/

//构造函数
var pageNation = {
    /**
     * 初始化方法，url-后台代码地址,clom-表格的基本信息,chinesename-中文名,colname-数据项命名,wide[short|middle|long]-数据项长度
     */
    init : function(option){
        pageNation.op = option;
        pageNation.op.param = {pageIndex:1},
        pageNation.op.tablename = 'pagetable';
        pageNation.op.pagename = 'pageDiv';
        pageNation.countPage =1;
        pageNation.total =1;
        pageNation.createHTML();
        pageNation.page();
    }//添加编辑的切换开关 ：I代表INSERT U代表UPDATE
    // switchoverIU:'I'
    
}

// 创建前台HTML页面
pageNation.createHTML = function(){
    var bodyhtml ='';
    //标题行
    bodyhtml += "<div style='width:100%;' ><h3 style = 'margin-left:5%;margin-right: auto;' >"+pageNation.op.title+"</h3></div><div class = 'maindiv' ><table>";
    var wide = '';
    /**
     * 生成模糊查询输入框
     */
    // $(pageNation.op.clom).each(function(i,items){
    //     if(items.wide =='short'){
    //         wide = '40px';
    //     }else if(items.wide =='middle'){
    //         wide = '60px';
    //     }else if(items.wide =='long'){
    //         wide = '130px';
    //     }
    //     bodyhtml += "<tr>"+
    //                     "<td>"+
    //                         "按"+items.chinesename+"查找：<input type='text'  style='width:"+wide+";' name='"+items.colname+"' />&nbsp;&nbsp;<input type='button' class='searchButton' onclick = 'pageNation.fuzzySearch();' value='搜索' />"+
    //                     "</td>";
       
    //     bodyhtml += "</tr>";
    // })
    bodyhtml += "<tr>"+
                    "<td>"+
                        "<div id='toolBar'>";

    $(pageNation.op.toolBar).each(function(i,items){
        bodyhtml += "<input type = 'button' class = 'searchButton' value='"+items['chinesename']+"' onclick = 'pageNation."+items['type']+"();' >";        
    })
    // var editurl= '/myrouter/staff';
    // var num =0;
    // $(pageNation.op.clom).each(function(i,items){
    //     if(items['type'] == 'IMAGE'){
    //         if(num==0){
    //             editurl += "?fileName[]="+items['colname'];
    //             num++;
    //         }else{
    //             editurl += "&fileName[]="+items['colname'];
    //         }
    //     }
    // })
    // console.log(editurl);
    // if()
    bodyhtml +="</div><div><table id='pagetable'  class = 'database' >"+
                        "</table></div>"+
                    "</td>"+
                "</tr>"+
            "</table>"+
            "<div id='pageDiv'>"+
            "</div></div><div class='editDiv' id='editDiv'><div class='editspan' ><form id='edit' enctype='multipart/form-data' action='#' method='post'>";
            // 添加修改的卡片，输入框的类型由数据类型决定，有VARCHAR、NUMBER、DATE、和状态列STATUS
            var inputtype;
            $(pageNation.op.clom).each(function(i,items){
                for(var k in items){
                    if(k == 'colname'){
                        if(items[k] == pageNation.op.primaryKey){
                            bodyhtml += "<div id = 'input'><div><span>"+items['chinesename']+"</span>:&nbsp;&nbsp;<input id='"+items[k]+"' name='"+items[k]+"' readonly='readonly' ></input></div>";
                            bodyhtml += "<input id='"+items[k]+"' name='primaryKey' style='display:none' value='"+pageNation.op.primaryKey+"' ></input>";
                            bodyhtml += "<input  name='returnUrl' style='display:none' value='"+window.location.href+"' ></input>";
                        }else{
                            if(items['type']=='DATE'){
                                inputtype = 'date';
                                bodyhtml += "<div><span>"+items['chinesename']+"</span>:&nbsp;&nbsp;<input id='"+items[k]+"' name='"+items[k]+"' type='"+inputtype+"' style ='width:120px;' title = '"+items['chinesename']+"' value='' /></div>";
                            }else if(items['type']=='VARCHAR'){
                                inputtype = 'text';
                                bodyhtml += "<div><span>"+items['chinesename']+"</span>:&nbsp;&nbsp;<input id='"+items[k]+"' name='"+items[k]+"' type='"+inputtype+"' style ='width:120px;' title = '"+items['chinesename']+"' value='' /></div>";
                                
                            }else if(items['type']=='NUMBER'){
                                inputtype = 'number';
                                bodyhtml += "<div><span>"+items['chinesename']+"</span>:&nbsp;&nbsp;<input id='"+items[k]+"' name='"+items[k]+"' type='"+inputtype+"' style ='width:120px;' title = '"+items['chinesename']+"' value='' /></div>";
                            }else if(items['type']=='status'){
                                bodyhtml += "<div><span>"+items['chinesename']+"</span>:&nbsp;&nbsp;";
                                for(var x in items['pool']){
                                    bodyhtml += "<input type='radio' name = '"+items[k]+"' style ='width:15px;' value = '"+items['pool'][x]+"'/>"+x;
                                }
                                pageNation.pageNationState = items[k];
                                bodyhtml +="</div>";
                            }else if(items['type']=='IMAGE'){
                                bodyhtml += "<div><span>"+items['chinesename']+"</span>:&nbsp;&nbsp;";
                                bodyhtml += "<input id='"+items[k]+"' type='file' name = 'IMAGE' style ='width:15px;'  />";
                                bodyhtml +="</div>";
                            }
                        }
                    }
                }
            });
    bodyhtml +="</div><br><br><input type = 'submit' class='searchButton' value = '提交' >&nbsp;&nbsp;<input class='searchButton' type='reset' value='重置'>&nbsp;&nbsp;<input type='button' class='searchButton' value='关闭' onclick='pageNation.close();'></form></div></div>";
    $("#"+pageNation.op.positionId).html(bodyhtml);
}

//模糊 查询功能，向param 中添加查询条件
pageNation.fuzzySearch = function (){
    var searcher = {};
    $(pageNation.op.clom).each(function(i,items){
        searcher[items.colname] = $("[name = "+items.colname+"]").val();
    })
    pageNation.op.param = {pageIndex:1,'searcher':searcher};
    pageNation.page();
}

//  用于填充前台的表格，以及分页的内容
 pageNation.page = function (){
    op = pageNation.op;
    var url;
    $(op.url).each(function(i,items){
        for(var j in items){
            if(j=='select'){
                url = items[j];
            }
        }
    });
    op.param.selectCondition=pageNation.op.selectCondition;
    $.ajax({
        method:'post',
        url:url,
        data:op.param,
        success:function(data){
            //填充表格主体
            var wide = '';
            var tableTr ="<tr>";
            $(op.clom).each(function(i,items){
                if(items.wide =='short'){
                    wide = '40px';
                }else if(items.wide =='middle'){
                    wide = '60px';
                }else if(items.wide =='long'){
                    wide = '130px';
                }
                tableTr += "<td style = 'width:"+wide+";' >"+items.chinesename+"</td>";
            });
            $(op.operation).each(function(i,items){
                if(items.wide =='short'){
                    wide = '40px';
                }else if(items.wide =='middle'){
                    wide = '60px';
                }else if(items.wide =='long'){
                    wide = '130px';
                }
                tableTr +="<td style = 'width:"+wide+";' >"+items.chinesename+"</td>";
            })
            tableTr +="</tr>";
            //操作的方法名
            var functionName = '';
            // 表格具体的数据填充部分
            $(data.rows).each(function(i,items){
                tableTr += "<tr>";
                $(op.clom).each(function(i,t){
                    if(t.type == 'IMAGE'){
                        tableTr += "<td><img style = 'width:80px;' src='"+items[t.colname]+"' alt='未上传图片' ></td>";
                    }else{
                        tableTr += "<td>"+items[t.colname]+"</td>";
                    }
                });
                $(op.operation).each(function(i,k){
                    //对应该绑定的函数进行筛选
                    tableTr +="<td><input type = 'button' class='searchButton' value='"+k.chinesename+"' onclick = 'pageNation."+k.type+"(this);' ></input></td>";
                });
                tableTr += "</tr>";
            });

            $('#'+op.tablename).html(tableTr);
            //填充表格主体结束
            var pageTr ='';
            // 填充分页
            pageTr +=  "<ul><li><a href = 'javascript:pageNation.firstPage();' >首页</a></li>&nbsp;"+
            "<li><a href='javascript:pageNation.upPage();' >上一页</a></li>&nbsp; "+
            "<input type='text' style='width:15px;float: left;margin-left: 5px;' id='jump' value="+data.pageIndex+" onchange='pageNation.pagechange();' /> &nbsp;"+
            "<li><a href='javascript:pageNation.downPage("+data.countPage+");' >下一页</a></li> &nbsp;"+
            "<li><a href = 'javascript:pageNation.lastPage("+data.countPage+");' >尾页</a></li></ul> &nbsp;"+
            "当前"+data.pageIndex+"页,总共"+data.countPage+"页,共"+data.total+"条";
            $('#'+op.pagename).html(pageTr);
            // 分页结束
        }
    });
}

// 分页跳转函数
pageNation.jumppage = function (pageIndex){
    var searcher = {};
    $(pageNation.op.clom).each(function(i,items){
        if(items.colname!=pageNation.pageNationState){
            searcher[items.colname] = $("[name = "+items.colname+"]").val();
        }
    })
    pageNation.op.param = {pageIndex:pageIndex,'searcher':searcher};
    pageNation.page();
}

// 绑定跳转页面的函数
pageNation.pagechange = function (){
    pageNation.jumppage($('#jump').val());
}

// 绑定上一页
pageNation.upPage = function (){
    var pageIndex = $('#jump').val();
    if((pageIndex-1)>0){
        pageNation.jumppage(pageIndex-1);
    }else{
        alert('已经到第一页了');
        pageNation.jumppage(pageIndex);
    }
    
}

// 绑定下一页
pageNation.downPage = function(pagesum){
    var pageIndex = $('#jump').val();
    if((Number(pageIndex)+1)<=pagesum){
        pageNation.jumppage(Number(pageIndex)+1);
    }else{
        alert('已经到最后一页了');
        pageNation.jumppage(pageIndex);
    }
}

// 绑定首页
pageNation.firstPage = function(){
    pageNation.jumppage(1);
}

// 绑定尾页
pageNation.lastPage = function(pagesum){
    pageNation.jumppage(pagesum);
}

//关闭编辑页
pageNation.close = function(){
    $("#input input[type!=radio][name!=primaryKey][name!=returnUrl]").val('');
    $('#editDiv').css('display','none');
}

//删除
pageNation.delete = function(btn){
    var tr = btn.parentNode.parentNode;
    var primaryKeyCell;
    $(op.clom).each(function(i,items){
        if(items.colname == op.primaryKey){
            primaryKeyCell = i;
        }
    });
    var url;
    $(op.url).each(function(i,items){
        for(var j in items){
            if(j=='delete'){
                url = items[j];
            }
        }
    });
    var primaryKey = $('#pagetable')[0].rows[tr.rowIndex].cells[primaryKeyCell].innerText;
    $.ajax({
        method:'post',
        url:url,
        data:{primaryKey:op.primaryKey,primaryKeyName:primaryKey},
        success:function(data){
            if(data.result == 'succeed'){
                pageNation.firstPage();
            }
        }
    });
}

//编辑
pageNation.update = function(btn){
    // pageNation.switchoverIU = "U";
    $("#input input[type!=radio][name!=primaryKey][name!=returnUrl]").val('');
    var url;
    $(op.url).each(function(i,items){
        for(var j in items){
            if(j=='update'){
                url = items[j];
            }
        }
    });
    var num =0;
    $(pageNation.op.clom).each(function(i,items){
        if(items['type'] == 'IMAGE'){
            if(num==0){
                url += "?fileName[]="+items['colname'];
                num++;
            }else{
                url += "&fileName[]="+items['colname'];
            }
        }
    })
    console.log(url)
    $("#edit").attr('action',url);
    var tr = btn.parentNode.parentNode;
    $(pageNation.op.clom).each(function(i,items){
        for(var j in items){
            if(j == 'colname'){
                if(items[j] == pageNation.op.primaryKey){//主键不可编辑
                    $("#"+items[j]).val($(tr.cells[i]).html());
                }else if(items['type'] == 'status'){//状态需要处理
                    $($("input:radio[name="+pageNation.pageNationState+"]")).each(function(x,y){
                        if(x == $(tr.cells[i]).html()){
                            $(y).attr('checked','ture');
                        }
                    })
                }else if(items['type'] == 'IMAGE'){//IMAGE不需要处理
                }else if(items['type'] == 'DATE'){//日期格式需要处理
                    var date = new Date($(tr.cells[i]).html());
                    var Y = date.getFullYear();
                    if((Number(date.getMonth())+1)<10){
                        if(Number(date.getMonth()+1)>1){
                            var M = '0'+(Number(date.getMonth())+1);
                        }else if(Number(date.getMonth())==1){
                            var M = '0'+(Number(date.getMonth()));
                        }
                    }else{
                        var M = date.getMonth()+1;
                    }
                    if((Number(date.getDate())-1)<10){
                        if(Number(date.getDate())>1){
                            var D = '0'+(Number(date.getDate())-1);
                        }else{
                            var D = '0'+(Number(date.getDate()));
                        }
                    }else{
                        var D = Number(date.getDate())-1;
                    }
                    $("#"+items[j]).val(Y+'-'+M+'-'+D);
                }else{
                    $("#"+items[j]).val($(tr.cells[i]).html());
                }
            }
        }
    });
    $('#editDiv').css('display','block');
}

//添加
pageNation.insert = function(){
    // pageNation.switchoverIU = "I";
    $("#input input[type!=radio][name!=primaryKey][name!=returnUrl]").val('');
    
    var url;
    $(op.url).each(function(i,items){
        for(var j in items){
            if(j=='insert'){
                url = items[j];
            }
        }
    });
    var num =0;
    $(pageNation.op.clom).each(function(i,items){
        if(items['type'] == 'IMAGE'){
            if(num==0){
                url += "?fileName[]="+items['colname'];
                num++;
            }else{
                url += "&fileName[]="+items['colname'];
            }
        }
    })
    $("#edit").attr('action',url);
    $('#editDiv').css('display','block');
}

pageNation.selectedredio = function (a){
    $($("input:radio[name="+pageNation.pageNationState+"]")).each(function(x,y){
        if(y!=a){

            $(y).removeAttr("checked");
        }
    })
    $(a).attr('checked','true');
}